<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\CardFriendlyLinks;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CardLinkController extends Controller
{
    /**
     * @var User
     */
    private $user = null;

    public function __construct()
    {
        $this->user = Auth::user();
    }
    /**
     * 名片列表
     * @param CardFriendlyLinks $cardFriendlyLinks
     * @return \Illuminate\Http\Response
     */
    public function index(CardFriendlyLinks $cardFriendlyLinks)
    {
        $links = $cardFriendlyLinks->where('user_id', '=',$this->user->id)->orderByDesc('created_at')->get();

        $data = [];
        foreach ($links as $link){
            $data[] = [
                'id' => $link->id,
                'cover' => $link->card->head_picture,
                'name' => $link->card->user_name,
                'profession' => $link->card->profession,
                'industry' => $link->card->industry,
                'company' => $link->card->company,
                'created_at' => $link->created_at->format('Y-m-d')
            ];
        }
        return $this->renderJson($data);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'holders' => 'required'
        ], [
            'required' => ':attribute不能为空'
        ], [
            'holders' => '名片夹'
        ]);

        $holders = $request->input('holders');
        $data = [];
        foreach ($holders as $holder){
            $r = DB::table('card_friendly_links')->where('user_id',$this->user->id)->where('friend_card_id', $holder)->first();
            if ($r != null){
                continue;
            }
            $data[] = [
                'user_id' => $this->user->id,
                'friend_card_id' => $holder
            ];
        }

        $res = DB::table('card_friendly_links')->insert($data);
        if ($res){
            return $this->success();
        }
        return $this->error('添加失败');
    }

    public function destroy($id, CardFriendlyLinks $cardFriendlyLinks)
    {
        $cardLink = $cardFriendlyLinks->findOrFail($id);
        try {
            $res = $cardLink->delete();
            if ($res){
                return $this->success();
            }
        } catch (\Exception $e) {
        }
        return $this->error('删除失败');
    }
}
